<?php
namespace control;
/*
*公文收文类
*/


class officialDocumentGetClass extends adIndexClass
{
    private const title = '公文收文';
    private const page = 'officialDocumentGet';
    private const table = 'official_document';
    public const workFlowOption = ['待签收', '待办理', '办理中', '已办结'];
    private array $urgentLevelOption = ['平急', '加急', '特急'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'allSearch':
                $tr = [
                    'preText'      => [
                        'name'  => "发文字号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type' => [
                        'name'  => "公文种类",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'title'  => [
                        'name'  => "标题",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'secretLevel'         => [
                        'name'  => '密级',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'urgentLevel'          => [
                        'name'  => '紧急程度',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'workFlow'          => [
                        'name'  => '状态',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'isArchive'          => [
                        'name'  => '归档状态',
                        'width' => 200,
                        'sort' => 1,
                    ]
                ];
                break;
            case 'completedSearch':
                $tr = [
                    'preText'      => [
                        'name'  => "发文字号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type' => [
                        'name'  => "公文种类",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'title'  => [
                        'name'  => "标题",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'secretLevel'         => [
                        'name'  => '密级',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'urgentLevel'          => [
                        'name'  => '紧急程度',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'revokeStid'          => [
                        'name'  => '办结人',
                        'width' => 200,
                    ],
                    'passTime'          => [
                        'name'  => '办结时间',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'workFlow'          => [
                        'name'  => '状态',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
                break;
            case 'processSearch':
                $tr = [
                    'preText'      => [
                        'name'  => "发文字号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type' => [
                        'name'  => "公文种类",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'title'  => [
                        'name'  => "标题",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'secretLevel'         => [
                        'name'  => '密级',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'urgentLevel'          => [
                        'name'  => '紧急程度',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'approverId'          => [
                        'name'  => '当前办理人',
                        'width' => 200,
                    ],
                    'commitTimePrevious'          => [
                        'name'  => '下发时间',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'workFlow'          => [
                        'name'  => '状态',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
                break;
            case 'pendingSearch':
                $tr = [
                    'preText'      => [
                        'name'  => "发文字号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type' => [
                        'name'  => "公文种类",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'title'  => [
                        'name'  => "标题",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'secretLevel'         => [
                        'name'  => '密级',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'urgentLevel'          => [
                        'name'  => '紧急程度',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'approverId'          => [
                        'name'  => '当前节点',
                        'width' => 200,
                    ],
                    'commitTime'          => [
                        'name'  => '提交审批时间',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'workFlow'          => [
                        'name'  => '状态',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
                break;
            default:
                $tr = [
                    'preText'      => [
                        'name'  => "发文字号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type' => [
                        'name'  => "公文种类",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'title'  => [
                        'name'  => "标题",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'secretLevel'         => [
                        'name'  => '密级',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'urgentLevel'          => [
                        'name'  => '紧急程度',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'copyWorkFlow'          => [
                        'name'  => '发文状态',
                        'width' => 150,
                    ],
                    'signStid'          => [
                        'name'  => '签发人',
                        'width' => 150,
                    ],
                    'signTime'          => [
                        'name'  => '签发时间',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'workFlow'          => [
                        'name'  => '状态',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }
    /**
     * 查询表单
     *
     * @param string $workFlow
     * @return string
     */
    public function homeForm(string $workFlow): string
    {
        //生成查询表单
        $dateTitle = '创建日期';
        if ($workFlow == '待签收') {
            $dateTitle = "签收日期";
        } elseif ($workFlow == '待办理') {
            $dateTitle = "提交审批时间";
        } elseif ($workFlow == '办理中') {
            $dateTitle = "下发日期";
        } elseif ($workFlow == '已办结') {
            $dateTitle = "办结日期";
        }
        $array = [
            [
                [
                    "发文字号" => text(array("name" => "preText")),
                    "公文种类"     => select(array("name" => "type", "option" => explode("，", para("officialDocumentType")))),
                    "标题" => text(array("name" => "title")),
                ],
                [
                    '密级'   => select(array("name" => "secretLevel", "option" => explode('，',para('secretLevelOption')))),
                    "紧急程度" => select(array("name" => "urgentLevel", "option" => $this->urgentLevelOption)),
                    $dateTitle   => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ];
        if ($workFlow == '全部') {
            $array[0][] = [
                '状态'   => select(array("name" => "workFlow", "option" => self::workFlowOption)),
                "归档状态" => select(array("name" => "isArchive", "option" => ['未归档', '已归档'])),
            ];
        }
        //生成查询表单
        return $this->tableShow($array,1);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('待签收');
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*客户列表-查询条件*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $url = root . "control/adIndex.html?cla=" . self::page . "&fun=detail";
        $button = "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{})\" class='spanButton'>确认签收</span>\n";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('新建" . self::title . "','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "preText" => $this->post('preText'),//发文字号
            "title" => $this->post('title'),//标题
        );
        //全等查询数组
        $equal = array(
            'classify'=>'收文',
            'workFlow' => '待签收',
            "type" => $this->post('type'),//公文种类
            "secretLevel" => $this->post('secretLevel'),
            "urgentLevel" => $this->post('urgentLevel'),
        );

        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'));
        }
        if (!$this->power(self::page,'seeAll')){
            $and .= self::seeSelf(self::page);
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("draftForm", "draftId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page . "&fun=detail";
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "draftId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                'browse' => array('title' => '预览', 'click' => "window.open('" . root . "control/adIndex.html?cla=officialDocumentModel&fun=preview&table=official_document&&id={$array['id']}')")
            );
            if ($array['copyId'] !='edit'){
                unset($dominate['edit']);
            }
            $liButton[] = $this->dominate($dominate);
            $copy = query(self::table,"id = '$array[copyId]'");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "copyWorkFlow":
                        $row[] = $copy['workFlow'];
                        break;
                    case "signStid":
                        $row[] = self::findStaff($array['signStid']);
                        break;
                    case "signTime":
                        $row[] = self::null($copy['signTime']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 150),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='draftForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    /**
     * 批量签收
     */
    public function stateSwitch(): bool|string
    {
        $formName = 'draftForm';
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否确认签收所选的公文？",
            ),
            array(
                must . "签收时间：" => text(array('name' => 'signTime', 'laydate' => [], 'value' => $this->date)),
            ),
        )));
        //返回
        return $this->layer(array("title" => "签收", "height" => 210, "html" => $html, 'formTwo' => $formName));
    }

    /**
     * 批量签收
     */
    public function stateSwitchEdit(): bool|string
    {
        $idArr = $this->post('id')?[$this->post('id')]:$this->post('draftId');
        if (static::is_null_array($idArr)) {
            $json['warn'] = "请选择数据";
        } elseif (empty($this->post('signTime'))) {
            $json['warn'] = '请选择签收时间';
        } else {
            $x = 0;
            $text = '';
            foreach ($idArr as $id) {
                $info = query(self::table, "id = '$id'");
                if ($info['workFlow'] != '待签收') {
                    $text .= $this->control['name'] . "签收了公文【{$info['title']}】， id：{$id} 失败：不是待签收状态<br>";
                }elseif($info['stid'] != self::$stid){
                    $text .= $this->control['name'] . "签收了公文【{$info['title']}】， id：{$id} 失败：这不是您的公文<br>";
                }else{
                    $warn = update(array('table' => self::table, 'field' => ['workFlow' => '待办理', 'signTime' => $this->post('signTime'), 'signStid' => self::$stid], 'where' => " id = '$id'"));
                    if ($warn == '更新成功') {
                        $x++;
                        //清除待办
                       backlogEnd(array(
                           "stid" => self::$stid,
                           "typeId" => $info['id'],
                       ));
                        $text .= $this->control['name'] . "签收了公文【{$info['title']}】， id：{$id}<br>";
                    } else {
                        $text .= $this->control['name'] . "签收了公文【{$info['title']}】， id：{$id} 失败，签收失败<br>";
                    }
                }
            }
            if ($text) {
                //添加日志
                $this->logText(["type" => self::page, "text" => $text]);
            }
            $_SESSION['warn'] = "成功签收了{$x}个公文，详情请查看系统日志";
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function processOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('办理中');
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 办理中
     *
     */
    public function process(): bool|string
    {
        $html = $this->processOptions(false);
        //控件
        $button = "";
        if ($this->power('documentGetProcess', "edit")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','press',{})\" class='spanButton'>催办</span>\n";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 办理中
     * @return bool|string
     */
    public function processSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "preText" => $this->post('preText'),//发文字号
            "title" => $this->post('title'),//标题
        );
        //全等查询数组
        $equal = array(
            'classify'=>'收文',
            'workFlow' => '办理中',
            "type" => $this->post('type'),//公文种类
            "secretLevel" => $this->post('secretLevel'),
            "urgentLevel" => $this->post('urgentLevel'),
        );

        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'));
        }
        if (!$this->power('documentGetProcess','seeAll')){
            $and .= self::seeSelf('documentGetProcess');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("abolishedForm", "abolishedId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "abolishedId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
                'browse' => array('title' => '预览', 'click' => "window.open('" . root . "control/adIndex.html?cla=officialDocumentModel&fun=preview&table=official_document&&id={$array['id']}')")
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "approverId":
                        $audit = query('audit',"targetId = '$array[id]'");
                        $row[] = self::findStaff(explode(',', $audit['approverId']));
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 150),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='abolishedForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 催办
     */
    public function press(): bool|string
    {
        $formName = 'abolishedForm';
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "提示：" => "是否催办所选公文？",
            ),
        )));
        //返回
        return $this->layer(array("title" => "催办", "height" => 150, "html" => $html, 'formTwo' => $formName));
    }

    /**
     * 催办
     */
    public function pressEdit(): bool|string
    {
        $idArr = $this->post('abolishedId');

        if (static::is_null_array($idArr)) {
            $json['warn'] = "请选择数据";
        } else {
            $x = 0;
            $text = '';
            foreach ($idArr as $id) {
                $info = query(self::table, "id = '$id'");
                $audit = query('audit', " targetId = '$id'");
                if (!$audit['id']){
                    $text .= $this->control['name'] . "催办了公文【{$info['title']}】， id：{$id} 失败，未在办理中<br>";
                }else{
                    $approver = explode(',', $audit['approverId']);
                    // 审批人列表
                    $approverArr = self::filterArray($approver);
                    foreach ($approverArr as $stid) {
                        $warn = static::update([
                            'table' => 'backlog',
                            'field' => [
                                'urging' => '是',
                                'time' => $this->time,
                            ],
                            'where' => " stid = '$stid'  AND typeId = '$audit[id]' AND workFlow = '待处理' ;",
                        ]);
                        if ($warn == '更新成功') {
                            $x++;
                            $text .= $this->control['name'] . "催办公文【{$info['title']}】， id：{$id}成功<br>";
                        } else {
                            $text .= $this->control['name'] . "催办公文【{$info['title']}】， id：{$id} 失败，更新待办失败<br>";
                        }
                    }
                }
            }
            if ($text) {
                //添加日志
                $this->logText(["type" => 'documentGetProcess', "text" => $text]);
            }
            $_SESSION['warn'] = "成功催办了{$x}个公文，详情请查看系统日志";
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function completedOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('已办结');
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 已办结
     *
     */
    public function completed(): bool|string
    {
        $html = $this->completedOptions(false);
        //控件
        $button = "";
        if ($this->power('documentGetCompleted', "archive")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','addArchive',{formName:'completedForm'})\" class='spanButton'>加入待归档</span>\n";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 已办结
     * @return bool|string
     */
    public function completedSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "preText" => $this->post('preText'),//发文字号
            "title" => $this->post('title'),//标题
        );
        //全等查询数组
        $equal = array(
            'classify'=>'收文',
            'workFlow' => '已办结',
            "type" => $this->post('type'),//公文种类
            "secretLevel" => $this->post('secretLevel'),
            "urgentLevel" => $this->post('urgentLevel'),
        );
        $and = '';
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'),field: 'passTime');
        }
        if (!$this->power('documentGetCompleted','seeAll')){
            $and .= self::seeSelf('documentGetCompleted');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'abandTime',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("completedForm", "completedId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "completedId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
                'browse' => array('title' => '预览', 'click' => "window.open('" . root . "control/adIndex.html?cla=officialDocumentModel&fun=preview&table=official_document&&id={$array['id']}')")
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "revokeStid":
                        $row[] = self::findStaff($array['revokeStid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 150),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='completedForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 加入待归档
     */
    public function addArchive(): bool|string
    {
        $formName = $this->post('formName');
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否将所选的公文加入待归档？",
            ),
        )));
        //返回
        return $this->layer(array("title" => "加入待归档", "height" => 155, "html" => $html, 'formTwo' => $formName));
    }

    /**
     * 加入待归档
     */
    public function addArchiveEdit(): bool|string
    {
        $idArr = $this->post('completedId');
        if (!$this->power('documentGetCompleted', "archive")) {
            $json['warn'] = "你没有" . self::title . "的加入待归档权限";
        } elseif (static::is_null_array($idArr)) {
            $json['warn'] = "请选择数据";
        }else {
            $x = 0;
            $text = '';
            foreach ($idArr as $id) {
                $info = query(self::table, "id = '$id'");
                if ($info['isArchive'] != '待归档'){
                    $text .= $this->control['name'] . "归档公文【{$info['title']}】， id：{$id} 失败，不是待归档状态<br>";
                }elseif($info['copyId'] !='edit'){
                    $text .= $this->control['name'] . "归档公文【{$info['title']}】， id：{$id} 失败，此公文不是新增的收文公文<br>";
                }elseif(static::total(array('table'=>'archive',"where"=>"targetId = '$info[id]'")) >0){
                    $text .= $this->control['name'] . "归档公文【{$info['title']}】， id：{$id} 失败，此公文已加入待归档<br>";
                }else{
                    if ($info['copyId'] =='edit'){
                        $warn = static::insert(array(
                            'table'=>'archive',
                            'field'=>[
                                'id'=>self::getId(),
                                'type'=>'公文收文',
                                'targetId'=>$id,
                                'orderNo'=>$info['preText'],
                                'name'=>$info['title'],
                                'pageNum'=>$info['pageNum'],
                                'partNum'=>$info['partNum'],
                                'level'=>$info['secretLevel'],
                                'transferStid'=>self::$stid,
                                'transferDate'=>$this->date,
                                'transferDept'=>self::findStaffDepartment(self::$stid,'id'),
                                'workFlow'=>'待归档',
                                'fileDate'=>$info['issueDate'],
                            ]
                        ));
                    }else{
                        $copy = query(self::table,"id = '$info[copyId]'");
                        $warn = static::insert(array(
                            'table'=>'archive',
                            'field'=>[
                                'id'=>self::getId(),
                                'type'=>'公文收文',
                                'targetId'=>$id,
                                'orderNo'=>$copy['preText'],
                                'name'=>$copy['title'],
                                'pageNum'=>$copy['pageNum'],
                                'partNum'=>$copy['partNum'],
                                'level'=>$copy['secretLevel'],
                                'transferStid'=>self::$stid,
                                'transferDate'=>$this->date,
                                'transferDept'=>self::findStaffDepartment(self::$stid,'id'),
                                'workFlow'=>'待归档',
                                'fileDate'=>$copy['issueDate'],
                            ]
                        ));
                    }
                    if ($warn == '新增成功') {
                        $x++;
                        $text .= $this->control['name'] . "归档公文【{$info['title']}】， id：{$id}<br>";
                    } else {
                        $text .= $this->control['name'] . "归档公文【{$info['title']}】， id：{$id} 失败，更新失败<br>";
                    }
                }
            }
            if ($text) {
                //添加日志
                $this->logText(["type" => 'documentGetCompleted', "text" => $text]);
            }
            $_SESSION['warn'] = "成功将{$x}个公文加入了待归档，详情请查看系统日志";
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function pendingOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('待办理');
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 待办理
     *
     */
    public function pending(): bool|string
    {
        $html = $this->pendingOptions(false);
        $button = "";
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    public function pendingSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "preText" => $this->post('preText'),//发文字号
            "title" => $this->post('title'),//标题
        );
        //全等查询数组
        $equal = array(
            'classify'=>'收文',
            'workFlow' => '待办理',
            "type" => $this->post('type'),//公文种类
            "secretLevel" => $this->post('secretLevel'),
            "urgentLevel" => $this->post('urgentLevel'),
        );

        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'),field:'commitTime');
        }
        if (!$this->power('documentGetPending','seeAll')){
            $and .= self::seeSelf('documentGetPending');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("auditForm", "auditId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "auditId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
                'browse' => array('title' => '预览', 'click' => "window.open('" . root . "control/adIndex.html?cla=officialDocumentModel&fun=preview&table=official_document&&id={$array['id']}')")
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "approverId":
                        $audit = query('audit', "targetId = '$array[id]'");
                        $row[] = self::findStaff(explode(',', $audit['approverId']));
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 150),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //控件
        $button = "";
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='auditForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function allOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('全部');
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 全部
     */
    public function all(): bool|string
    {
        $html = $this->allOptions(false);
        $button = "";
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    public function allSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "preText" => $this->post('preText'),//发文字号
            "title" => $this->post('title'),//标题
        );
        //全等查询数组
        $equal = array(
            'classify'=>'收文',
            "type" => $this->post('type'),//公文种类
            "secretLevel" => $this->post('secretLevel'),
            "urgentLevel" => $this->post('urgentLevel'),
            "workFlow" => $this->post('workFlow'),
            "isArchive" => $this->post('isArchive'),
        );
        $and='';
        if (!$this->power('documentGetAll','seeAll')){
            $and .= self::seeSelf('documentGetAll');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)).$and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['id'] . "')"),
                'browse' => array('title' => '预览', 'click' => "window.open('" . root . "control/adIndex.html?cla=officialDocumentModel&fun=preview&table=official_document&&id={$array['id']}')")
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 150),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='issuedForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     *选择模板
     * @return bool|string
     */
    public function addMaterial(): bool|string
    {
        $html =
            select(array("name" => "type", "title" => "公文种类", 'option' => explode("，", para("officialDocumentType")))) .
            text(array("name" => "templateName", "title" => "模板名称"));
        $button = "<input style='margin-left: 5px' onclick=\"chooseTemplate()\" type='button' class='searchSub' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "选择模板", "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     *添加物料
     */
    public function addMaterialSearch(): bool|string
    {
        $like = [
            'name' => $this->post('templateName'),
        ];
        $equal = [
            'state' => '启用',
            'type' => $this->post('type'),
        ];
        $where = search(["like" => $like, "=" => $equal]);
        $page = $this->page([
            "table" => "official_document_template",
            "where" => $where,
            'pageNum' => 50,
            "order" => "`time` ASC",
        ]);
        //获取表头
        $tr[] = ['', '公文种类', '模板名称'];
        //获取记录
        foreach ($page['array'] as $array) {
            $tr[] = array(
                "<input name='mxId' value='$array[id]' type='radio'>",
                $array['type'],
                $array['name'],
            );
        }
        $json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMaterialEdit(): bool|string
    {
        $templateId = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($templateId)) {
            $json['warn'] = '请选择模板';
        } else {
            $template = query('official_document_template', "id = '$templateId'");
            $json['data'] = $template;
            $json['data']['tag'] = componentClass::singleInput(array('list' => explode(',', $template['tag'])));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id')?:suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
        ];
        $button[] = [
            "name" => "从模板新建",
            "type" => "点击事件",
            "title" => "从模板新建",
            'fun' => "layer('" . self::page . "','addMaterial',{})",
        ];
        $data['button'] = $this->tableShowButton($button);
        $body           = $this->edit4([
            '基本信息' => [
                [
                    must . "公文种类：" => select(["name" => "type", 'title' => '请选择', 'option' => explode('，', para('officialDocumentType')), "value" => $info['type']]),
                    must . "标题：" => text(["name" => "title", 'class' => 'text', "value" => $info['title']]),
                    "发文字号：" => text(array('name' => 'prefix','title'=>'发文字',  'value' => $info['prefix'])) . '【' . text(array('name'=>'prefixYear','title'=>'年份','class'=>'textPrice','laydate'=>['type'=>'year'],'value'=>$info['prefixYear'])) . '】 ' . text(array('name' => 'list', 'class' => 'textPrice', 'value' => $info['list'])) . '号',
                ],
                [
                    must . "紧急程度：" => radio(["name" => "urgentLevel", 'value' => $this->urgentLevelOption, "checked" => $info['urgentLevel'] ?: '平急']),
                    "保密期限：" => text(["name" => "secretTime", 'class' => 'text', "value" => $info['secretTime']]),
                    must . "密级：" => radio(["name" => "secretLevel", 'value' => explode('，',para('secretLevelOption')), "checked" => $info['secretLevel'] ?: '内部']),
                ],
                [
                    "摘要：" => textarea(["name" => "summary", 'class' => 'textarea', "value" => $info['summary']])
                ],
                [
                    "页数：" => text(["name" => "pageNum", "value" => $info['pageNum']]),
                    "份数：" => text(["name" => "partNum", "value" => $info['partNum']]),
                    "是否用印：" => radio(["name" => "isSeal", 'value' => ['是', '否'], "checked" => $info['isSeal'] ?: '否']),
                    must . "发文单位：" => text(["name" => "issueUnit", 'class' => 'text', "value" => $info['issueUnit']]),
                ],
                [
                    "发文日期：" => text(["name" => "issueDate", 'laydate' => [], "value" => $info['issueDate']]),
                    must . "主送单位：" => text(["name" => "department", 'class' => 'text', "value" => $info['department']]),
                    //must . "主送人：" => componentClass::staffSelector($info['selector'])
                    "抄送单位：" => text(["name" => "copyDept", 'class' => 'text', "value" => $info['copyDept']]),
                    "印发单位：" => text(["name" => "issuedDept", 'class' => 'text', "value" => $info['issuedDept']]),
                ],
                [
                    "主题词：" => "<div id='mainTag' class='full'>" . componentClass::singleInput(array('list' => explode(',', $info['tag']))) . "</div>",
                ],
                [
                    must . "正文：" => textarea(["name" => "content", 'class' => 'textarea', "value" => $info['content']]),
                ],
                [
                    "附件：" => fileUploadClass::addFileComponent($info['id'], '公文收文', self::page, self::page . 'EditForm'),
                ],
            ]
        ]);
        //表单
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $data['html'].=<<<eof
<style>
.textPrice{width: 100px !important;}
</style>
eof;

        $data['html'] .= $this->editJs();
        //返回
        return $this->tab($data);
    }

    public function editJs(): string
    {
        return <<<eof
<script>
function chooseTemplate(){
     $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMaterialEdit',$("form[name='mxForm']").serialize(),function(res) {
         if (res.warn ==2){
             $("#officialDocumentSendAddMaterial").hide();
            $(".edit4 [name='type']").val(res.data.type);
            $(".edit4 [name='title']").val(res.data.title);
            $(".edit4 [name='issueUnit']").val(res.data.issueUnit);
            $(".edit4 [name='prefix']").val(res.data.prefix);
            $(".edit4 [name='department']").val(res.data.department);
            $(".edit4 [name='copyDept']").val(res.data.copyDept);
            $(".edit4 [name='issuedDept']").val(res.data.issuedDept);
            $(".edit4 [name='content']").val(res.data.content);
            $("#mainTag").html(res.data.tag);
         }else{
             msg(res.warn);
         }
    },'json');
}
</script>
eof;

    }

    public function editEdit()
    {
        $fileIdArr = $this->post('fileId');
        $id = $this->post('id') ?: self::getId();
        $label_name = $this->post('label_name') ?: [];
        $field = [
            'type' => $this->post('type'),
            'title' => $this->post('title'),
            'summary' => $this->post('summary'),
            'prefixYear'=>$this->post('prefixYear'),
            'secretLevel' => $this->post('secretLevel'),
            'secretTime' => $this->post('secretTime'),
            'issueDate' => $this->post('issueDate'),
            'urgentLevel' => $this->post('urgentLevel'),
            'pageNum' => $this->post('pageNum'),
            'partNum' => $this->post('partNum'),
            'list' => $this->post('list'),
            'issueUnit' => $this->post('issueUnit'),
            'prefix' => $this->post('prefix'),
            'department' => $this->post('department'),
            'copyDept' => $this->post('copyDept'),
            'issuedDept' => $this->post('issuedDept'),
            'content' => $this->post('content'),
            'tag' => implode(',', $label_name),
//            'member' => $this->post('member'),//员工选择器
        ];

        $annotation = [
            'type' => '公文种类',
            'title' => '标题',
            'secretLevel' => '密级',
            'urgentLevel' => '紧急程度',
            'issueUnit' => '发文单位',
            'department' => '主送单位',
//            'member' => '主送人',
            'content' => '正文',
        ];
        $rules = [
            'type' => 'required',
            'title' => 'required',
            'secretLevel' => 'required',
            'urgentLevel' => 'required',
            'issueUnit' => 'required',
//            'member' => 'required',
            'department' => 'required',
            'content' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::total(array('table' => self::table, 'where' => "title = '$field[title]' and id !='$id'")) > 0) {
            $json['warn'] = '已存在此标题的公文';
        }elseif(!empty($field['prefix']) && (empty($field['prefixYear']) || empty($field['list']))){
            $json['warn'] = '请完整填写发文字号';
        } else {
            if (!$info['id']) {
                $field['preText'] = $field['prefix']?$field['prefix'] . " [" . date('Y') . "] {$field['list']}号":'';
                $field = array_merge($field, [
                    'id' => $id,
                    'state' => '草稿',
                    'workFlow' => '待签收',
                    'classify' => '收文',
                    'prefixYear' => date('Y'),
                    'stid' => $this->control['stid'],
                    'copyId'=>'edit',
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $field['preText'] = $field['prefix'] . " [{$info['prefixYear']}] {$field['list']}号" .
                    $json['warn'] = static::update([
                        "table" => self::table,
                        "field" => $field,
                        "where" => $where,
                    ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加主表ID到附件表
                if (is_array($fileIdArr)) {
                    update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 提交审批后触发
     * @param $data
     */
    public function commitAfter($data)
    {
        update(array('table' => self::table, 'field' => ['workFlow' => '办理中', 'commitTime' => $this->time], 'where' => "id = '$data[id]'"));
    }

    /**
     * 审核通过后触发
     * @param $data
     */
    public function auditAfter($data){
        update(array('table' => self::table, 'field' => ['revokeStid' => self::$stid], 'where' => "id = '$data[id]'"));
    }
    /**
     * 审核按钮
     *
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
          if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'],'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => [
                    "act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'name' => '公文收文',
                        'table' => self::table,
                        'process' => [
                            // 预览函数
                            'detail' => [
                                'cla' => $this->get('cla'),
                                'fun' => 'detail',
                            ],
                            //执行发起时验证函数
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //完成发起后执行函数
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => 'commitAfter',
                                'data' => ['id' => $info['id']]
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        // 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => [
                    "act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                        // 当前状态
                        'state' => $info['state'],
                        // 变更
                        'field' => ['state', 'workFlow'],   //变更字段 可多个
                        'value' => [
                            'state' => ['草稿', '已通过'],
                            'workFlow' => ['待办理', '已办结'],
                        ],
                        // 审核时回调
                        'process' => [
                            //执行首次审核时验证
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //执行末次审核后处理
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => 'auditAfter',
                                'data'=>['id'=>$info['id']]
                            ],
                        ],
                    ], 320)),
                ],
                'style' => 'li-btn-blue-bg',
            ];
        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                        // 当前状态
                        'state' => $info['state'],
                        // 变更
                        'field' => ['state', 'workFlow'],   //变更字段 可多个
                        'value' => [
                            'state' => ['草稿'],
                            'workFlow' => ['待办理']
                        ],
                        'process' => [
                            //完成发起后执行函数
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        return $button;
    }

    /*客户管理-客户详情页*/
    public function detail()
    {
        $info = query(self::table, "id = '" . $this->get('id') . "'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            $copy = query(self::table,"id = '$info[copyId]'");
            //按钮
            $button = [];
            if ($this->power(self::page, "edit") && $info['state']=='草稿' && $info['copyId'] == 'edit') {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "顶部页卡",
                    "title" => "编辑",
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $info['id'],
                ];
            }
            //按钮
            $button[] = [
                "name" => "预览",
                "type" => "点击事件",
                "title" => "预览",
                'fun' => "window.open('" . root . "control/adIndex.html?cla=officialDocumentModel&fun=preview&method=preview&table=".self::table."&id={$info['id']}')"
            ];
            if ($this->power(self::page, "del") && $info['state']=='草稿' && ($info['copyId'] =='edit' || $copy['workFlow'] =='已撤销' || $copy['workFlow'] =='已废止')) {
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            if ($info['workFlow'] =='待签收'){
                //按钮
                $button[] = [
                    "name" => "签收",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "stateSwitch",
                    "post" => ["id" => $info['id']],
                ];
            }
            //审核按钮
            $button = array_merge($this->auditButton($info),$button);
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '基本信息' => array(
                    array(
                        "公文种类" => $info['type'],
                        "标题" => $info['title'],
                        "发文字号" => $info['preText'],
                    ),
                    array(
                        "摘要" => pre($info['summary']),
                    ),
                    array(
                        "紧急程度" => $info['urgentLevel'],
                        "保密期限" => $info['secretTime'],
                        "密级" => $info['secretLevel'],
                        "页数" => $info['pageNum'],
                    ),
                    array(
                        "份数" => $info['partNum'],
                        "是否用印" => $info['isSeal'],
                        "发文日期" => $info['issueDate'],
                        "发文单位" => $info['issueUnit'],
                    ),
                    array(
                        "主送单位" => $info['department'],
                        "抄送单位" => $info['copyDept'],
                        "印发单位" => $info['issuedDept'],
                    ),
                    array(
                        "主送人" => componentClass::showSelector($info['selector'])
                    )
                ),
                '附件' => array(
                    array(
                        fileUploadClass::showFile($info['id'], '公文收文')
                    )
                ),
                "系统信息" => array(
                    array(
                        "拟制人" => self::findStaff($info['stid']),
                        "签发时间" => $copy['signTime'],
                        "签收时间" => self::null($info['signTime']),
                        "提交审批时间" => self::null($info['commitTime']),
                    ),
                    array(
                        "开始办理时间" => self::null($info['commitTime']),
                        '办结时间' => self::null($info['passTime']),
                        "归档时间" => self::null($info['revokeTime']),
                        "状态" => $info['workFlow'],
                    ),
                ),
                '流程' => array(
                    array(
                        auditClass::auditRecord(self::table, $info['id']),
                    ),
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                $copy = query(self::table,"id = '$info[copyId]'");
                if ($info['state'] != '草稿') {
                    //返回
                    $warn = "删除失败：不是草稿状态";
                }elseif(!$this->power(self::page,'seeAll') && $info['stid'] !=self::$stid){
                    $warn = "删除失败：这不是您的收文";
                } elseif(!empty($copy['id']) && !in_array($copy['workFlow'],['已废止','已撤销'])){
                    $warn = "删除失败：发文未废止或未撤销";
                }else {
                    $result = find(array('table' => 'file', 'where' => "targetId = '$id'"));
                    foreach ($result['array'] as $file) {
                        fileDelete($file['src']);
                    }
                    //删除附件
                    delete(array("table" => "file", "where" => " targetId = '$id' "));
                    //删除audit表记录
                    delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message", "where" => " typeId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " khid = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }


}
